package com.hy.springboot.common.utils;

import java.util.Map;
import java.util.concurrent.Callable;

/**
 * 无返回值 异步任务
 * @author lccsetsun
 * @since 2024/1/31 11:10
 **/
public class ThreadMdcUtil {
	public static void setTraceIdIfAbsent() {
		if (MDCUtils.get() == null) {
			MDCUtils.set();
		}
	}

	public static <T> Callable<T> wrap(final Callable<T> callable, final Map<String, String> context) {
		return () -> {
			if (context == null) {
				MDCUtils.clear();
			} else {
				MDCUtils.setContextMap(context);
			}
			setTraceIdIfAbsent();
			try {
				return callable.call();
			} finally {
				MDCUtils.clear();
			}
		};
	}

	public static Runnable wrap(final Runnable runnable, final Map<String, String> context) {
		return () -> {
			if (context == null) {
				MDCUtils.clear();
			} else {
				MDCUtils.setContextMap(context);
			}
			//设置traceId
			setTraceIdIfAbsent();
			try {
				runnable.run();
			} finally {
				MDCUtils.clear();
			}
		};
	}
}
